package net.suncaper.psychological.service.impl;

import net.suncaper.psychological.service.ITimeConfigService;
import net.suncaper.psychological.model.domain.TimeConfig;
import net.suncaper.psychological.mapper.TimeConfigMapper;
import net.suncaper.psychological.mapper.impl.TimeConfigMapperImpl;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.util.Date;

/**
 * 时间配置服务层实现类
 */
public class TimeConfigServiceImpl implements ITimeConfigService {
    
    private TimeConfigMapper timeConfigMapper = new TimeConfigMapperImpl();
    
    // 常量定义
    private static final String WORKING_HOURS_TYPE = "WORKING_HOURS";
    private static final String INTERVAL_TYPE = "INTERVAL";

    @Override
    public boolean saveTimeConfig(TimeConfig timeConfig) {
        if (timeConfig == null) {
            return false;
        }
        
        // 验证配置是否有效
        if (!validateTimeConfig(timeConfig)) {
            return false;
        }
        
        // 设置创建时间和更新时间
        Date now = new Date();
        timeConfig.setCreatedTime(now);
        timeConfig.setUpdatedTime(now);
        
        return timeConfigMapper.save(timeConfig);
    }

    @Override
    public boolean deleteTimeConfigById(Long id) {
        if (id == null || id <= 0) {
            return false;
        }
        return timeConfigMapper.deleteById(id);
    }

    @Override
    public boolean updateTimeConfig(TimeConfig timeConfig) {
        if (timeConfig == null || timeConfig.getId() == null) {
            return false;
        }
        
        // 验证配置是否有效
        if (!validateTimeConfig(timeConfig)) {
            return false;
        }
        
        // 设置更新时间
        timeConfig.setUpdatedTime(new Date());
        
        return timeConfigMapper.update(timeConfig);
    }

    @Override
    public TimeConfig getTimeConfigById(Long id) {
        if (id == null || id <= 0) {
            return null;
        }
        return timeConfigMapper.findById(id);
    }

    @Override
    public List<TimeConfig> getAllTimeConfigs() {
        return timeConfigMapper.findAll();
    }

    @Override
    public List<TimeConfig> getTimeConfigsByType(String configType) {
        if (configType == null || configType.trim().isEmpty()) {
            return new ArrayList<>();
        }
        return timeConfigMapper.findByConfigType(configType);
    }

    @Override
    public List<TimeConfig> getTimeConfigsByIsActive(Boolean isActive) {
        if (isActive == null) {
            return new ArrayList<>();
        }
        return timeConfigMapper.findByIsActive(isActive);
    }

    @Override
    public List<TimeConfig> getTimeConfigsByTypeAndIsActive(String configType, Boolean isActive) {
        if (configType == null || configType.trim().isEmpty() || isActive == null) {
            return new ArrayList<>();
        }
        return timeConfigMapper.findByConfigTypeAndIsActive(configType, isActive);
    }

    @Override
    public boolean updateIsActiveByIds(List<Long> ids, Boolean isActive) {
        if (ids == null || ids.isEmpty() || isActive == null) {
            return false;
        }
        return timeConfigMapper.updateIsActiveByIds(ids, isActive);
    }

    @Override
    public List<TimeConfig> getWorkingHoursConfigs() {
        return getTimeConfigsByType(WORKING_HOURS_TYPE);
    }

    @Override
    public List<TimeConfig> getIntervalConfigs() {
        return getTimeConfigsByType(INTERVAL_TYPE);
    }

    @Override
    public List<TimeConfig> getActiveWorkingHoursConfigs() {
        return getTimeConfigsByTypeAndIsActive(WORKING_HOURS_TYPE, true);
    }

    @Override
    public List<TimeConfig> getActiveIntervalConfigs() {
        return getTimeConfigsByTypeAndIsActive(INTERVAL_TYPE, true);
    }

    @Override
    public List<Map<String, Object>> getTimeConfigMaps(String configType) {
        if (configType == null || configType.trim().isEmpty()) {
            return new ArrayList<>();
        }
        return timeConfigMapper.findMapsByConfigType(configType);
    }

    @Override
    public boolean createDefaultTimeConfigs() {
        try {
            // 创建默认工作时间配置
            createDefaultWorkingHoursConfigs();
            
            // 创建默认间隔时间配置
            createDefaultIntervalConfigs();
            
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean validateTimeConfig(TimeConfig timeConfig) {
        if (timeConfig == null) {
            return false;
        }
        
        // 验证必填字段
        if (timeConfig.getConfigType() == null || timeConfig.getConfigType().trim().isEmpty()) {
            return false;
        }
        
        if (timeConfig.getName() == null || timeConfig.getName().trim().isEmpty()) {
            return false;
        }
        
        // 验证配置类型
        if (!WORKING_HOURS_TYPE.equals(timeConfig.getConfigType()) && 
            !INTERVAL_TYPE.equals(timeConfig.getConfigType())) {
            return false;
        }
        
        // 验证工作时间配置
        if (WORKING_HOURS_TYPE.equals(timeConfig.getConfigType())) {
            return validateWorkingHoursConfig(timeConfig);
        }
        
        // 验证间隔时间配置
        if (INTERVAL_TYPE.equals(timeConfig.getConfigType())) {
            return validateIntervalConfig(timeConfig);
        }
        
        return true;
    }
    
    /**
     * 创建默认工作时间配置
     */
    private void createDefaultWorkingHoursConfigs() {
        List<TimeConfig> defaultConfigs = new ArrayList<>();
        
        // 上午工作时间
        TimeConfig morningConfig = new TimeConfig(
            WORKING_HOURS_TYPE,
            "上午工作时间",
            "08:00",
            "12:00",
            60,
            60,
            "1,2,3,4,5",
            "上午工作时间段，8:00-12:00",
            true
        );
        defaultConfigs.add(morningConfig);
        
        // 下午工作时间
        TimeConfig afternoonConfig = new TimeConfig(
            WORKING_HOURS_TYPE,
            "下午工作时间",
            "13:00",
            "17:00",
            60,
            60,
            "1,2,3,4,5",
            "下午工作时间段，13:00-17:00",
            true
        );
        defaultConfigs.add(afternoonConfig);
        
        // 晚上工作时间
        TimeConfig eveningConfig = new TimeConfig(
            WORKING_HOURS_TYPE,
            "晚上工作时间",
            "18:00",
            "21:00",
            60,
            60,
            "1,2,3,4,5,6,7",
            "晚上工作时间段，18:00-21:00",
            false
        );
        defaultConfigs.add(eveningConfig);
        
        // 保存默认配置
        for (TimeConfig config : defaultConfigs) {
            if (timeConfigMapper.findByConfigType(config.getConfigType()).isEmpty()) {
                timeConfigMapper.save(config);
            }
        }
    }
    
    /**
     * 创建默认间隔时间配置
     */
    private void createDefaultIntervalConfigs() {
        List<TimeConfig> defaultConfigs = new ArrayList<>();
        
        // 咨询时间间隔
        TimeConfig consultationInterval = new TimeConfig(
            INTERVAL_TYPE,
            "咨询时间间隔",
            null,
            null,
            60,
            50,
            null,
            "咨询时间间隔，每次咨询50分钟，间隔10分钟",
            true
        );
        defaultConfigs.add(consultationInterval);
        
        // 初访时间间隔
        TimeConfig initialVisitInterval = new TimeConfig(
            INTERVAL_TYPE,
            "初访时间间隔",
            null,
            null,
            30,
            25,
            null,
            "初访时间间隔，每次初访25分钟，间隔5分钟",
            true
        );
        defaultConfigs.add(initialVisitInterval);
        
        // 保存默认配置
        for (TimeConfig config : defaultConfigs) {
            if (timeConfigMapper.findByConfigType(config.getConfigType()).isEmpty()) {
                timeConfigMapper.save(config);
            }
        }
    }
    
    /**
     * 验证工作时间配置
     */
    private boolean validateWorkingHoursConfig(TimeConfig timeConfig) {
        if (timeConfig.getStartTime() == null || timeConfig.getEndTime() == null) {
            return false;
        }
        
        // 验证时间格式（简单验证）
        if (!timeConfig.getStartTime().matches("\\d{2}:\\d{2}") || 
            !timeConfig.getEndTime().matches("\\d{2}:\\d{2}")) {
            return false;
        }
        
        // 验证开始时间小于结束时间
        String[] startParts = timeConfig.getStartTime().split(":");
        String[] endParts = timeConfig.getEndTime().split(":");
        
        int startHour = Integer.parseInt(startParts[0]);
        int startMinute = Integer.parseInt(startParts[1]);
        int endHour = Integer.parseInt(endParts[0]);
        int endMinute = Integer.parseInt(endParts[1]);
        
        int startTotal = startHour * 60 + startMinute;
        int endTotal = endHour * 60 + endMinute;
        
        return startTotal < endTotal;
    }
    
    /**
     * 验证间隔时间配置
     */
    private boolean validateIntervalConfig(TimeConfig timeConfig) {
        if (timeConfig.getIntervalMinutes() == null || timeConfig.getDuration() == null) {
            return false;
        }
        
        // 验证间隔时间和持续时间都大于0
        if (timeConfig.getIntervalMinutes() <= 0 || timeConfig.getDuration() <= 0) {
            return false;
        }
        
        // 验证间隔时间大于等于持续时间
        return timeConfig.getIntervalMinutes() >= timeConfig.getDuration();
    }
} 